﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Data;
using System.Text;
using System.ServiceModel.Activation;
using WcfServicePush.Service.Contract;
using WcfServicePush.Model;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Net;
using Newtonsoft.Json;
using cn.jpush.api;
using cn.jpush.api.push;
using cn.jpush.api.push.mode;
using cn.jpush.api.push.notification;


namespace WcfServicePush.Service.Service
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
    public class Push : IPush
    {

        private static string app_key = "f6840f2f392ecc418565a1aa";
        private static string master_secret = "650804f4a392fd1875121ce9";
        /// <summary>
        /// 验证服务是否可用
        /// </summary>
        public string verify(string data)
        {
            return "Hello WcfService:" + data;
        }

        #region 推送相关
        /// <summary>
        /// 发起推送（自定义消息）
        /// </summary>
        public Boolean reqPush(BaseModel model)
        {
            JPushClient client = new JPushClient(app_key, master_secret);
            MessageResult result = client.SendPush(pushData(model));
            return result.isResultOK();
        }

        /// <summary>
        /// 测试推送服务
        /// </summary>
        public string reqPushTest(string alias)
        {
            BaseModel model = new BaseModel();
            model.alias = "69517DEB#3A92#39BA#E053#3FB0010AC550";
            model.title = "测试reqPush";
            model.message = "测试reqPush";
            model.json = "{action:test}";
            string resultStr = "Hello WcfService Push Test :";
            try
            {
                Boolean result = reqPush(model);
                if (result)
                {
                    resultStr = "OK";
                }
                else
                {
                    resultStr = resultStr + result;
                }
            }
            catch (Exception e)
            {
                resultStr = resultStr + e.ToString();
            }
            return resultStr;
        }

        public static PushPayload pushData(BaseModel model)
        {
            PushPayload pushPayload = new PushPayload();
            pushPayload.platform = Platform.android();
            pushPayload.audience = Audience.s_alias(model.alias);
            //是否显示通知栏
            pushPayload.notification = Notification.android(model.title, model.message);
            //自定义消息
            pushPayload.message = Message.content(JsonConvert.SerializeObject(model));
            return pushPayload;
        }
        #endregion
    }
}